import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import Cookies from 'js-cookie'
const getDefaultState = () => {
  return {
    token: getToken() || '',
    userInfo: {},
    userLevel:'',
    activity_id:'',
    searchValue:''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  // 更新用户信息
  SET_USERINFO(state, payload) {
    state.userInfo = payload
  },
  // 移出用户信息
  REMOVE_USERINFO(state) {
    state.userInfo = {}
  },
  SET_USER_LEVEL: (state, level) => {
    state.userLevel = level;
  },
  SET_ACTIVITY_ID(state, activity_id) {
    state.activity_id = activity_id;
  },
  SET_SEARCH_VALUE(state, search) {
    state.searchValue = search;
  },
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { account, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ account: account.trim(), password: password }).then(response => {
        // console.log(response);
        commit('SET_TOKEN', response.token)
        setToken(response.token)
        commit('SET_USER_LEVEL', response.path)
        Cookies.set('level', response.path)
        Cookies.set('activity_id', response.activity_id)
        commit('SET_ACTIVITY_ID', response.activity_id);
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        console.log(response);
        if (!response) {
          return reject('Verification failed, please Login again.')
        }
        commit('SET_USERINFO', response.info)
        // Cookies.set('userInfo', response.info)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => { 
     removeToken() // must remove  token  first
     resetRouter()
     commit('RESET_STATE')
     resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      // 移除时间戳
      commit('RESET_STATE')
      resolve()
    })
  },
    //搜索缓存
    setSearchValue({ commit }, value) {
      return new Promise((resolve) => {
        
        commit('SET_SEARCH_VALUE', value);
        resolve();
      });
      
    }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

